package es.ats.codington.web.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import es.ats.codington.festival.domain.People;
import es.ats.codington.festival.domain.Visitor;
import es.ats.codington.festival.exceptions.ServiceException;
import es.ats.codington.festival.services.VisitorService;

/**
 * Servlet implementation class UpdatePeopleServlet
 */
@WebServlet("/UpdatePeopleServlet")
public class UpdatePeopleServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public UpdatePeopleServlet() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    
    /**
     * Invokes the action "updatevisitor.jsp"
     */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		RequestDispatcher rd = request.getRequestDispatcher("updatevisitor.jsp");
		rd.forward(request, response);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	
	/**
	 * Method invoked when a visitor is updated
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		int idVisitor = 0;
        
		HttpSession session = request.getSession(true);
		
		/**
		 * Parameters obtained form
		 */
		String n1=request.getParameter("name1");
		String n2=request.getParameter("name2");
		String d=request.getParameter("dni");
		String em=request.getParameter("email");
		String ph=request.getParameter("phone");
		String ad=request.getParameter("address");
		
		String n=(String) session.getAttribute("username");

		
		VisitorService service = new VisitorService();
		
		Visitor v = new Visitor();
		v.setUserName(n);
		
		idVisitor = service.getIdVisitor(v);
			
		
		People people = new People();
		
		people.setFirstName(n1);
		people.setLastName(n2);
		people.setDni(d);
		people.setEmail(em);
		people.setPhoneNumber(ph);
		people.setAddress(ad);
		people.setIdPeople(idVisitor);
	
		
		
		try {
			/**
			 * The visitor is updated
			 */
	    	service.updateVisitor(people);
	    	/**
			 * Invokes the action "personalvisitor.jsp"
			 */
	    	request.getRequestDispatcher("personalvisitor.jsp").forward(request, response);
	 
		
		}
		 catch (ServiceException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		    
		    out.close(); 
		    
		
	
	}

}
